import { GetAddress, PostAddress } from "../../api/address";
import { PostOrder } from "../../api/order";
import { conpon } from "../../api/user";
import { err } from "../../utils/console";
import { toast } from "../../utils/wxapi";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    description: "",
    show: false,
    list: [],
    item: {},
    model_name: "",
    address_id: "",
    fault: [] as any,
    fault_show: false,
    conponlist: [] as any,
    conpon_show: false,
    contitle: "",
    coupon_id: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    let model_name = wx.getStorageSync("model_name");
    this.setData({ model_name });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.addresslist();
    this.conpon();
  },
  async conpon() {
    try {
      const res = await conpon({ all: 1 });
      console.log(res);
      if (res.statusCode === 200) {
        this.setData({
          conponlist: res.data,
        });
      }
    } catch (error) {
      err(error);
    }
  },
  fault_list() {
    let fault_list = wx.getStorageSync("fault_list");
    const fault = [] as any;
    console.log(fault_list);
    fault_list.forEach((e: any) => {
      if (e.sel) {
        e.children.forEach((v: any) => {
          if (v.sel) {
            let label = v.label;
            let price = v.price;
            fault.push({ label, price });
          }
        });
      }
    });
    this.setData({ fault, fault_show: true });
  },
  async addresslist() {
    try {
      const res = await GetAddress({ all: 1 });
      console.log(res);
      if (res.statusCode === 200) {
        this.setData({ list: res.data });
      } else {
        err(res.data);
      }
    } catch (error) {
      err(error);
    }
  },
  async postAddress() {
    try {
      const res: any = await this.chooseAddressAsync();
      if (res.errMsg === "chooseAddress:ok") {
        const {
          cityName,
          countyName,
          detailInfo,
          provinceName,
          telNumber,
          userName,
        } = res;
        const data = {
          name: userName,
          phone: telNumber,
          address: provinceName + cityName + countyName + detailInfo,
        };
        const resp: any = await PostAddress(data);
        console.log(resp);
        if (resp.statusCode === 200) {
          toast("添加成功");
          this.addresslist();
        } else {
          err(res.data);
        }
      }
    } catch (error) {
      err(error);
    }
  },
  chooseAddressAsync(): Promise<any> {
    return new Promise((resolve, reject) => {
      wx.chooseAddress({
        success: resolve,
        fail: reject,
      });
    });
  },
  seladd(e: any) {
    const { item } = e.currentTarget.dataset;
    this.setData({ item, address_id: item.id, show: false });
  },
  address() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false, fault_show: false, conpon_show: false });
  },
  add_conpon() {
    this.setData({ conpon_show: true });
  },
  sub_con(e: any) {
    const { contitle, coupon_id } = e.currentTarget.dataset;
    this.setData({ contitle, coupon_id, conpon_show: false });
  },
  async ding() {
    const res = await wx.getSetting({ withSubscriptions: true });
    console.log(res);
    const subscriptionsSetting = res.subscriptionsSetting;

    if (
      subscriptionsSetting &&
      subscriptionsSetting.mainSwitch === true &&
      subscriptionsSetting.itemSettings
    ) {
      if (
        subscriptionsSetting.itemSettings[
          "C0xvyOFwJVkhqKVlHXiYRolTHTb6CRW0CfPLddEmXM0"
        ] === "accept"
      ) {
        wx.reLaunch({ url: "/pages/weixiu/weixiu" });
      } else {
        this.getsub();
      }
    } else {
      this.getsub();
    }
  },
  getsub() {
    wx.requestSubscribeMessage({
      tmplIds: ["C0xvyOFwJVkhqKVlHXiYRolTHTb6CRW0CfPLddEmXM0"],
      success: () => {
        this.sub();
      },
      fail: (err) => {
        console.log(err);
      },
    });
  },
  vaildateForm() {
    const { description, address_id } = this.data;
    if (description === "") {
      toast("请填写备注");
      return false;
    } else if (address_id === "") {
      toast("请选择地址");
      return false;
    }

    return true;
  },
  sub() {
    if (this.vaildateForm()) {
      const { description, model_name, address_id, coupon_id } = this.data;
      const brand_name = wx.getStorageSync("brand_name") || "其他";
      const repair_type_id = wx.getStorageSync("repair_type_id") || [];
      const data = {
        description,
        brand_name: brand_name,
        model_name: model_name || "其他",
        address_id,
        repair_type_id,
        coupon_id,
      };
      PostOrder(data)
        .then((res: any) => {
          console.log(res);
          if (res.statusCode === 200) {
            toast("订单提交成功");
            wx.reLaunch({ url: "/pages/weixiu/weixiu" });
          } else {
            toast("订单提交失败");
          }
        })
        .catch((err: (arg0: any) => void) => {
          err(err);
          toast("订单提交失败，请稍后再试");
        });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
